package com.mszlu.blog.service.mq;

import com.alibaba.fastjson.JSON;
import com.mszlu.blog.service.ArticleService;
import com.mszlu.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
@Slf4j
@Component
public class ArticleListener {
    @Autowired
    private ArticleService articleService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct"),
            exchange = @Exchange(name = "blog-update-article", type = ExchangeTypes.DIRECT),
            key = {"key"}
    ))
    public void listenArticleUpdate(String msg){
        log.info("接收到消息"+msg);
//        System.out.println(msg);
        //加密 以防出现key过长以及字符转义获取不到的情况
        Result articleById = articleService.findArticleById(Long.valueOf(msg));
        msg = DigestUtils.md5Hex(msg);
        String redisKey = "view_article::ArticleController::findArticleById::"+msg;
        redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(articleById), Duration.ofMillis(5 * 60 * 1000));
        log.info("更新了缓存"+redisKey);
    }
}
